import { login, getInfo } from "@/api/user";

const state = {
  token: localStorage.getItem("token"),
  user: localStorage.getItem("user"),
  roles: [],
};

const mutations = {
  setToken: (state, token) => {
    state.token = token;
  },
  setRoles: (state, roles) => {
    state.roles = roles;
  },
  setUser: (state, user) => {
    state.user = user;
  },
};

const actions = {
  // 模拟用户登录
  login({ commit }, userInfo) {
    return login(userInfo).then((res) => {
      commit("setToken", res.data);
      commit("setUser", res.data);
      localStorage.setItem("token", res.data);
      localStorage.setItem("user", res.data);
    });
  },
  // 模拟获取用户角色信息
  getInfo({ commit, state }) {
    return getInfo(state.token).then(({ data: roles }) => {
      commit("setRoles", roles);
      return { roles };
    });
  },
  // 模拟清空令牌和角色状态
  resetToken({ commit }) {
    return new Promise((resolve) => {
      commit("setToken", "");
      commit("setUser", "");
      commit("setRoles", []);
      localStorage.removeItem("token");
      localStorage.removeItem("user");
      resolve();
    });
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
